<template>
  <el-card style="margin-bottom: 80px">
    <el-button
      class="back-home-button"
      type="primary"
      @click="goToHome"
      :icon="House"
      style="margin-bottom: 20px"
    >
      返回首页
    </el-button>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        border
        default-expand-all
      >
        <el-table-column prop="id" label="商品编号" width="100" />
        <el-table-column prop="name" label="商品名称" width="260" />
        <el-table-column prop="price" label="商品价格" width="100" />
        <el-table-column prop="stock" label="商品库存" width="100" />
        <el-table-column prop="description" label="商品简介" />
        <el-table-column prop="picture" label="商品图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.picture"
              :src="row.picture"
              fit="contain"
              style="display: flex; align-items: center; height: 60px"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200px">
          <template #default="{ row }">
            <el-button type="warning" @click="handleAddToCart(row)"
              >加入购物车</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        style="margin-top: 20px"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getGoodsList, getGoodsOnePage } from "../../api/api";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import config from "../../config";

const router = useRouter();
const tableData = ref([]);
const page = ref(1);
const pageSize = ref(2);
const total = ref(0);

onMounted(() => {
  loadGoodsList();
});

const loadGoodsList = async () => {
  try {
    const params = {
      page: page.value,
      pagesize: pageSize.value,
    };

    const [data, list] = await Promise.all([
      getGoodsOnePage(params),
      getGoodsList(),
    ]);

    tableData.value = data.map((item) => ({
      ...item,
      description: removeTags(item.description),
      picture: item.picture ? `${config.baseURL}${item.picture}` : "",
    }));

    total.value = list.length;
  } catch (error) {
    console.error("Failed to load goods list:", error);
    ElMessage.error("加载商品列表失败");
  }
};

const goToHome = () => {
  router.push('/');
};

const removeTags = (str) => str.replace(/<[^>]+>/g, "");

const handleCurrentChange = (value) => {
  page.value = value;
  loadGoodsList();
};

const handleAddToCart = (row) => {
  const userName = localStorage.getItem("userName");
  if (!userName) {
    ElMessage.warning("请先登录");
    router.push("/login");
    return;
  }

  let cart = JSON.parse(localStorage.getItem("cart") || "[]");
  const existingItem = cart.find((item) => item.id === row.id);

  if (existingItem) {
    existingItem.quantity += 1;
  } else {
    cart.push({
      id: row.id,
      title: row.name,
      price: row.price,
      picture: row.picture,
      quantity: 1,
    });
  }

  localStorage.setItem("cart", JSON.stringify(cart));
  ElMessage.success("已添加到购物车");
  router.go(0);
};
</script>